package a09_贪心算法;

import java.util.Arrays;

/**
 * <p>
 * a18_无重叠区间
 * </p>
 *
 * @author flyduck
 * @since 2025/1/15
 */
public class a18_无重叠区间 {
    public static void main(String[] args) {
        int[][] intervals = new int[][]{{1,2},{2,3},{3,4},{1,3}};
        eraseOverlapIntervals(intervals);
    }
    //按照左边界先排序
    //如果i的左边界 >= i-1的右边界 说明不重叠
    //如果i的左边界 < i-1的右边界 说明重叠
    // count++
    // i的右边界 = Math.min(i-1的右边界,i的右边界)
    public static int eraseOverlapIntervals(int[][] intervals) {
        intervals = Arrays.stream(intervals)
                .sorted((item1,item2) -> item1[0] - item2[0])
                .toArray(int[][]::new);
        int count = 0;
        for (int i = 1; i < intervals.length; i++) {
            if(intervals[i][0] < intervals[i-1][1] ){
                count++;
                intervals[i][1] = Math.min(intervals[i][1], intervals[i-1][1]);
            }
        }
        return count;
    }

}
